﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeTabling.Core;
using System.Data.SqlClient;
using System.Reflection;
using System.Data;

namespace TimeTabling.DAL
{
    public class GenericDAO<T> : IGenericDAO<T>
    {
        private string connectionString;

        private string entityName;
        private IList<string> fieldNames = new List<string>();

        public GenericDAO(string connectionString)
        {
            this.connectionString = connectionString;

            entityName = typeof(T).Name;
            fieldNames = typeof(T).GetProperties()
                        .Where(p=>string.Compare(p.PropertyType.Namespace, "system", true) == 0)
                        .Select(p => p.Name).ToList();
        }
        public void Add(T entity)
        {            
            string command = 
                string.Format("Insert {0} into {1} Values(@{2})", 
                    string.Join(",", fieldNames),
                    entityName, 
                    string.Join(",@", fieldNames)
                 );
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                SqlCommand sqlCommand = new SqlCommand(command, sqlConnection);
                foreach (var field in fieldNames)
                {
                    sqlCommand.Parameters.Add(
                        string.Format("@{0}", field),
                        typeof(T).GetProperty(field).GetValue(entity, null));
                }
                try
                {
                    sqlConnection.Open();
                    sqlCommand.ExecuteNonQuery();
                }
                finally
                {
                    if (sqlConnection.State != ConnectionState.Closed)
                    {
                        sqlConnection.Close();
                    }
                }
            }
        }

        public void Update(T entity)
        {
            throw new NotImplementedException();
        }

        public int Count()
        {
            throw new NotImplementedException();
        }

        public T Get(Guid id)
        {
            throw new NotImplementedException();
        }

        public IList<T> GetAll()
        {
            throw new NotImplementedException();
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }
    }
}
